from pandas_datareader import data
import numpy as np
import pandas as pd
import requests 
from collections import deque 
import json

def buylowsellhigh(fundTransactionData):
    data_ = pd.DataFrame(fundTransactionData)
    data_['target'] = data_['average_nav']
    data_['daily_difference'] = data_['target'].diff()
    data_['signal'] = 0.0
    data_['signal'][:] = np.where(data_['daily_difference'][:] > 0, 1.0, 0.0)
    data_['positions'] = data_['signal'].diff()
    return data_

def stockbuylowsellhigh(stockTransactionData):
    data_ = pd.DataFrame(stockTransactionData)
    data_ = data_.iloc[::-1]
    data_signal = pd.DataFrame(index=data_.index)
    data_signal['price'] = data_['close'].astype(float)
    data_signal['daily_difference'] = data_signal['price'].diff()
    data_signal['signal'] = 0.0
    data_signal['signal'][:] = np.where(data_signal['daily_difference'][:] > 0, 1.0, 0.0)
    data_signal['positions'] = data_signal['signal'].diff()
    data_['buysellsig'] = data_signal['positions']
    initial_capital = float(1000.0)
    positions = pd.DataFrame(index=data_signal.index).fillna(0.0)
    portfolio = pd.DataFrame(index=data_signal.index).fillna(0.0)
    positions['GOOG'] = data_signal['signal']
    portfolio['positions'] = (positions.multiply(data_signal['price'], axis=0))
    portfolio['cash'] = initial_capital - (positions.diff().multiply(data_signal['price'], axis=0)).cumsum()
    portfolio['total'] = portfolio['positions'] + portfolio['cash']
    data_['positions'] = portfolio['positions']
    data_['cash'] = portfolio['cash']
    data_['total'] = portfolio['total']
    print(data_)
    return data_

def get_fund_data(fcode, page, per, start_date, end_date):
    URL = "https://fundf10.eastmoney.com/F10DataApi.aspx"
    # defining a params dict for the parameters to be sent to the API 
    PARAMS = {"type": "lsjz", 
              "code": fcode, 
              "page": page, 
              "sdate": start_date, 
              "edate": end_date, 
              "per": per} 

    # sending get request and saving the response as response object 
    r = requests.get(url = URL, params = PARAMS) 

    data = r.text.lstrip("var apidata={ content:")
    datas = data.split(",records", 1)
    # print(datas[0])
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(datas[0], 'html5lib')
    data_list = []  # 结构: [dict1, dict2, ...], dict结构{'船名': ship_name, '航次': voyage, '提单号': bill_num, '作业码头': wharf}
    data_list = deque(data_list) 
    for idx, tr in enumerate(soup.find_all('tr')):
        if idx != 0:
            tds = tr.find_all('td')
            data_list.appendleft({
                'date': tds[0].contents[0].extract(),
                'average_nav': float(tds[1].contents[0].extract()), # 单位净值
                'accumulated_net': float(tds[2].contents[0].extract()), # 累积净值
                'daily_growth_rate': tds[3].contents[0].extract(), # 日增长率
                'subscription_status': tds[4].contents[0].extract(),
                'redemption_status': tds[5].contents[0].extract()
            })      
    return data_list

def get_stock_data(symbol_, scale_, ma_, datalen_):
    URL = "http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData"
    # defining a params dict for the parameters to be sent to the API 
    PARAMS = {
              "symbol": symbol_, 
              "scale": scale_, 
              "ma": ma_, 
              "datalen": datalen_
             } 
    # sending get request and saving the response as response object 
    r = requests.get(url = URL, params = PARAMS) 
    return json.loads(r.text)
